package org.example.chat.controller;

import com.github.tobato.fastdfs.FdfsClientConfig;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.MetaData;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.domain.proto.storage.DownloadByteArray;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import org.example.chat.api.CommonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.parameters.P;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

@RestController
@RequestMapping("/file")
public class FileUpDownController {

    @Autowired
    private FastFileStorageClient fastFileStorageClient;
    @Autowired
    private FdfsWebServer fdfsWebServer;
    @Value("${fdfs.thumb-image.width}")
    private Integer thumbWidth;
    @Value("${fdfs.thumb-image.height}")
    private Integer thumbHeight;

    @PostMapping("/upload")
    public CommonResult<Map<String,String>> upload(MultipartFile file, Boolean isCreateThumb) {
        try {
            String filename = file.getOriginalFilename();
            String suffix = filename.substring(file.getOriginalFilename().lastIndexOf(".") + 1);
            String regExp = "jpg|png|gif";
            if (!suffix.matches(regExp)) {
                return CommonResult.fail("只能上传png|jpg|gif格式的图片");
            }
            Set<MetaData> metaDatas = new HashSet<>();
            metaDatas.add(new MetaData("filename", filename));
            StorePath storePath = null;


            if (isCreateThumb) {
                // 生成缩略图
                storePath = fastFileStorageClient.uploadImageAndCrtThumbImage(file.getInputStream(), file.getSize(), suffix, metaDatas);
                // 缩略图文件后缀名

            } else {
                // 不生成缩略图
                storePath = fastFileStorageClient
                        .uploadFile(file.getInputStream(),file.getSize(),suffix ,metaDatas);
            }

            Map<String, String> data = new HashMap<>();
            StringBuilder sb = new StringBuilder();
            sb.append(fdfsWebServer.getWebServerUrl());
            sb.append(storePath.getFullPath());
            String bigImagePath = sb.toString();
            data.put("bigImagePath",bigImagePath);
            data.put("filename",filename);
            if (isCreateThumb) {
                // 缩略图文件后缀名
                StringBuilder s = new StringBuilder();
                s.append("_").append(thumbWidth).append("x").append(thumbHeight).append(".").append(suffix);
                String thumbImagePath = bigImagePath.substring(0,bigImagePath.lastIndexOf(".")) + s.toString();
                data.put("thumbImagePath", thumbImagePath);
             }


            return CommonResult.successNoMessage(data);
        } catch (Exception e) {
            return CommonResult.fail("上传失败");
        }
    }


    @PostMapping("/download")
    public void download(String filePath, HttpServletResponse response) {
        try {
            StorePath storePath = StorePath.parseFromUrl(filePath);
            byte[] data = fastFileStorageClient.downloadFile(storePath.getGroup(), storePath.getPath(), new DownloadByteArray());
//            response.setHeader("Content-Disposition","attachment;filename=" + URLEncoder.encode());
            response.getOutputStream().write(data);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @PostMapping("/delete")
    public void deleteFile(String filePath) {
        fastFileStorageClient.deleteFile(filePath);
    }
}
